package com.pphh.demo;

import com.pphh.demo.exception.BlockException;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Please add description here.
 *
 * @author huangyinhuang
 * @date 11/21/2018
 */
public class AtomicFlowControl extends FlowControl {

    private static AtomicInteger counter = new AtomicInteger(0);
    private final int max;

    public AtomicFlowControl(int max) {
        this.max = max;
    }

    @Override
    public void run() throws BlockException {
        int value = counter.incrementAndGet();
        if (value <= this.max) {
            // execute the test task
            test();
            counter.decrementAndGet();
        } else {
            throw new BlockException("task is blocked");
        }

    }
}
